package com.cfks.webviewdriver;

import android.webkit.ValueCallback;
import com.cfks.webviewdriver.error.ElementNotFound;
import java.util.concurrent.CountDownLatch;

public class Elements {
    private WebviewDriver wvd;
    private String name = "";
    public int length = 0;
    private int by = 0;
	private ElementNotFound exception = null;
    public Elements(final String name, int by, WebviewDriver wvd) throws ElementNotFound {
        this.wvd = wvd;
        this.name = name;
        this.by = by;
        if (by == By.by_classname) {
			final CountDownLatch latch = new CountDownLatch(1);
			wvd.getWebView().evaluateJavascript("javascript:(function() { let elements = document.getElementsByClassName('" + name + "'); return elements.length > 0; })()", new ValueCallback<String>() {
					@Override
					public void onReceiveValue(String value) {
						boolean isElementExists = Boolean.parseBoolean(value);
						if (!isElementExists) {
							exception = new ElementNotFound("getElementsByClassName " + name + " Not Found");
						}
						latch.countDown();
					}
				});
			try {
				latch.await();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
			if (exception != null) {
				throw exception;
			}
        }
    }
    public Element get(int n) throws ElementNotFound {
        return new Element(this.name, this.by, this.wvd, n);
    }
}
